/**
 * 全局Store统一配置
 * 提供从各个模块安全导入Store的机制
 */

// 定义默认备用Store，避免循环依赖
const DEFAULT_CACHE_GROUP = {
  CACHE_KEY: 'DEFAULT_RESOURCES_CACHE_KEY',
  CACHE_TIME: 30 * 60 * 1000
};

// 内联定义资源存储对象，避免路径导入问题
// 这个resourcesStore是内联定义的，不依赖于外部文件
const resourcesStore = {
  // 缓存配置（必须）
  CACHE_GROUP: {
    CACHE_KEY: 'RESOURCES_CACHE_KEY',
    CACHE_TIME: 30 * 60 * 1000 // 30分钟
  },
  
  // 状态属性
  loading: false,
  error: null,
  resourceList: [],
  currentResource: null,
  filter: { status: 'all', keyword: '' },
  pagination: { page: 1, size: 10, total: 0, hasMore: true },
  
  // 基本方法
  setLoading(loading) { 
    this.loading = loading; 
    console.log('[resourcesStore] 设置loading', loading);
  },
  
  setError(error) { 
    this.error = error; 
    console.log('[resourcesStore] 设置error', error);
  },
  
  setResourceList(list) { 
    this.resourceList = list || []; 
    console.log('[resourcesStore] 设置resourceList', list?.length || 0);
  },
  
  setCurrentResource(resource) { 
    this.currentResource = resource; 
    console.log('[resourcesStore] 设置currentResource', resource?.id);
  },
  
  // 模拟加载方法
  async loadResourceList(params = {}) {
    console.log('[resourcesStore] 加载资源列表', params);
    this.loading = true;
    this.error = null;
    
    try {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 模拟数据
      const mockData = Array(10).fill(0).map((_, i) => ({
        id: `resource-${i}`,
        name: `资源 ${i+1}`,
        type: i % 3 === 0 ? 'file' : 'folder',
        size: i * 1024,
        lastModified: new Date().toISOString()
      }));
      
      this.resourceList = mockData;
      this.pagination = {
        page: 1,
        size: 10,
        total: mockData.length,
        hasMore: false
      };
      this.loading = false;
      
      return mockData;
    } catch (error) {
      this.loading = false;
      this.error = error.message || '加载资源失败';
      console.error('[resourcesStore] 加载失败', error);
      throw error;
    }
  },
  
  // 重置方法
  reset() {
    console.log('[resourcesStore] 重置状态');
    this.loading = false;
    this.error = null;
    this.resourceList = [];
    this.currentResource = null;
    this.filter = { status: 'all', keyword: '' };
    this.pagination = { page: 1, size: 10, total: 0, hasMore: true };
  },
  
  // 初始化方法
  init() {
    console.log('[resourcesStore] 初始化完成');
    return this;
  }
};

// 备用资源存储对象实现（仅在标准化过程中无法使用内联定义时使用）
const backupResourcesStore = {
  // 必须包含CACHE_GROUP属性，防止"Cannot read property 'CACHE_GROUP' of undefined"错误
  CACHE_GROUP: DEFAULT_CACHE_GROUP,
  
  // 基本状态
  loading: false,
  error: null,
  resourceList: [],
  currentResource: null,
  filter: { status: 'all', keyword: '' },
  pagination: { page: 1, size: 10, total: 0, hasMore: true },
  
  // 基本方法
  setLoading(loading) { this.loading = loading; },
  setError(error) { this.error = error; },
  setResourceList(list) { this.resourceList = list || []; },
  setCurrentResource(resource) { this.currentResource = resource; },
  loadResourceList() { console.warn('[store_config.js] 使用备用resourceStore.loadResourceList'); return Promise.resolve([]); },
  reset() { console.warn('[store_config.js] 使用备用resourceStore.reset'); }
};

// 备用默认存储对象，防止未定义错误
const backupDefaultStore = {
  CACHE_GROUP: DEFAULT_CACHE_GROUP,
  loading: false,
  error: null,
  reset() { console.warn('[store_config.js] 使用备用defaultStore.reset'); },
  initialize() {
    console.warn('[store_config.js] 使用备用defaultStore.initialize');
    return this;
  }
};

let storeStandardizer;
try {
  storeStandardizer = require('../store/standardizer/store_standardizer.js');
} catch (e) {
  console.error('[store_config.js] 导入store_standardizer失败', e);
  // 提供备用实现
  storeStandardizer = {
    standardizeModuleStore: function(store, storeName) {
      console.warn(`[store_config.js] 使用备用standardizeModuleStore处理${storeName}`);
      if (!store) return backupDefaultStore;
      
      // 确保基本字段
      if (store.error === undefined) store.error = null;
      if (store.loading === undefined) store.loading = false;
      if (!store.reset) store.reset = function() { console.warn(`[store_config.js] ${storeName}.reset()`); };
      if (!store.CACHE_GROUP) {
        store.CACHE_GROUP = {
          CACHE_KEY: `${storeName.toUpperCase()}_CACHE_KEY`,
          CACHE_TIME: 30 * 60 * 1000
        };
      }
      return store;
    }
  };
}

// 标准化内联定义的资源存储
const standardizedResourcesStore = storeStandardizer.standardizeModuleStore(resourcesStore, 'resourcesStore');

// 导出标准化的Store
module.exports = {
  resourcesStore: standardizedResourcesStore,
  // 导出备用Store，供其他模块使用
  backupResourcesStore,
  backupDefaultStore
}; 